//
//  CartViewController.m
//  AmazingShopping
//
//  Created by Tan on 4/6/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "CartViewController.h"
#import "ProductDetailViewController.h"
#import "LoginViewController.h"
#import "OrderViewController.h"

@interface CartViewController ()

@end

@implementation CartViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    userInfoPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] userInfoPath];
    checkoutBarButton = [[UIBarButtonItem alloc]initWithTitle:@"Checkout" style:UIBarButtonItemStylePlain target:self action:@selector(checkout)];
}

- (void)viewWillAppear:(BOOL)animated{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    if ([productInCart count] > 0) {
        self.navigationItem.rightBarButtonItem = checkoutBarButton;
    }else{
        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    tableView = nil;
    [super viewDidUnload];
}

- (void)getProductData:(NSNotification *)noti{
    NSMutableArray *productIDArray;
    NSString *productIDs;
    NSMutableDictionary *userData = [[NSMutableDictionary alloc]initWithContentsOfFile:userInfoPath];
    if ([[noti name] isEqualToString:@"AddedProductInCart"]) {
        if (productInCart == nil) {
            productInCart = [[NSMutableArray alloc]init];
        }
        if (existProductInCartArray == nil) {
            existProductInCartArray = [[NSMutableArray alloc]init];
        }
        if ([existProductInCartArray indexOfObject:[[noti userInfo] valueForKey:@"ID"]] != NSNotFound) {
            for (NSMutableDictionary *object in [productInCart objectEnumerator]){
                if ([[object valueForKey:@"ID"] isEqualToString:[[noti userInfo] valueForKey:@"ID"]]) {
                    NSInteger qty = [[object valueForKey:@"Qty"] integerValue];
                    qty++;
                    [object setValue:[NSString stringWithFormat:@"%d", qty] forKey:@"Qty"];
                    break;
                }
            }
        }else{
            [productInCart addObject:[noti userInfo]];
            [existProductInCartArray addObject:[[noti userInfo] valueForKey:@"ID"]];
        }        
        [tableView reloadData];
        return;
    }else if ([[noti name] isEqualToString:@"ChangedUserStatus"] && !isLogin) {
        [productIDArray removeAllObjects];
    }else{
        productIDArray = [[NSMutableArray alloc] initWithArray:[[userData valueForKey:@"ProductInCart"] allKeys]];
        
        //Convert productIDs Array to String
        productIDs = @"";
        for (int i = 0; i < productIDArray.count; i++) {
            productIDs = [NSString stringWithFormat:@"%@%@%@", productIDs, seperatorString, [productIDArray objectAtIndex:i]];
        }
        
        //Get product data from server
        if (![productIDs isEqualToString:@""]) {
            serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
            ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/get_product", serverPath]]];
            [request addPostValue:productIDs forKey:@"product_id_list"];
            [request startAsynchronous]; 
        }else{
            [tableView reloadData];
        }
    }
}

- (void)checkout{
    OrderViewController *nextController = [[OrderViewController alloc]init];
    [self.navigationController pushViewController:nextController animated:YES];
}

#pragma mark Cart View Delegate
- (void)removeProductFromCart:(NSString *)productID{
    for (NSMutableDictionary *object in [productInCart objectEnumerator]){
        if ([[object valueForKey:@"ID"] isEqualToString:productID]) {
            [existProductInCartArray removeObject:[object valueForKey:@"ID"]];
            [productInCart removeObject:object];            
            break;
        }
    }
    NSMutableDictionary *userData = [[NSMutableDictionary alloc]initWithContentsOfFile:userInfoPath];
    NSMutableDictionary *productIDArray = [[NSMutableDictionary alloc] initWithDictionary:[userData valueForKey:@"ProductInCart"]];
    [productIDArray removeObjectForKey:productID];
    [userData setObject:productIDArray forKey:@"ProductInCart"];
    [userData writeToFile:userInfoPath atomically:YES];
    
    NSMutableDictionary *tempCart = [[NSMutableDictionary alloc]initWithDictionary:[userData valueForKey:@"ProductInCart"]];
    NSArray *qtyArray = [tempCart allValues];
    int qty = 0;
    for (int i = 0; i < qtyArray.count; i++) {
        qty += [[qtyArray objectAtIndex:i] integerValue];
    }
    
    [[[self.tabBarController.tabBar items] objectAtIndex:2] setBadgeValue:[NSString stringWithFormat:@"%d", qty]];
    
    [tableView reloadData];
}

#pragma mark ASIHTTPRequest Delegate
- (void)requestFailed:(ASIHTTPRequest *)request{
    
}

- (void)requestFinished:(ASIHTTPRequest *)request{
    NSData *data = [request responseData];
    JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
    productInCart = [jsonDecoder objectWithData:data];
    [tableView reloadData];
}

#pragma mark Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (productInCart == nil && !isLogin) {
        return 2;
    }
    return [productInCart count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!isLogin && productInCart.count == 0){
        switch ([indexPath row]) {
            case 0:
                return 100;
                break;
                
            default:
                return 40;
                break;
        }
    }else{
        return 125;
    }    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (!isLogin && productInCart == nil) {
        return nil;
    }else{
        if (section == 0) {
            if ([productInCart count] == 0) {
                return @"Your shopping cart is empty";
            }else{
                NSInteger qty = 0;
                for (int i = 0; i < productInCart.count; i++) {
                    NSInteger temp = [[[productInCart objectAtIndex:i] valueForKey:@"Qty"] integerValue];
                    qty += temp;
                }
                if (qty == 1) {
                    return @"1 item to buy now                   Qty";
                }
                return [NSString stringWithFormat:@"%ld items to buy now                Qty", (long)qty];
            }
        }else{
            return @"Items saved for later";
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (!isLogin && productInCart == nil) {
        UIView *customFooter = [[UIView alloc]initWithFrame:CGRectZero];
        return customFooter;
    }else{
        CGRect frame = [self->tableView rectForHeaderInSection:section];
        valuesOfCart = 0.0;
        for (int i = 0; i < productInCart.count; i++) {
            float price = [[[productInCart objectAtIndex:i] valueForKey:@"Price"] floatValue];
            NSInteger qty = [[[productInCart objectAtIndex:i] valueForKey:@"Qty"] integerValue];
            valuesOfCart += price * qty;
        }
        if (section == 0 && valuesOfCart > 0) {
            UIView *customFooter = [[UIView alloc]init];
            customFooter.backgroundColor = [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1];
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x + 200, frame.origin.y, 65, frame.size.height)];
            label.backgroundColor = [UIColor clearColor];
            label.font = [UIFont fontWithName:@"Helvetica" size:13];
            label.text = @"Subtotal = ";
            
            UILabel *priceLabel = [[UILabel alloc]initWithFrame:CGRectMake(frame.origin.x + 265, frame.origin.y, 70, frame.size.height)];
            priceLabel.backgroundColor = [UIColor clearColor];
            priceLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];
            [priceLabel setTextColor:[UIColor colorWithRed:170/255.0 green:10/255.0 blue:0/255.0 alpha:1.0]];
            if (valuesOfCart == 0.0) {
                priceLabel.text = @"N/A";
            }else{
                NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                [numberFormatter setMaximumFractionDigits:2];
                NSNumber *number = [NSNumber numberWithFloat:valuesOfCart];
                priceLabel.text = [NSString stringWithFormat:@"$%@", [numberFormatter stringFromNumber:number]];
            }
            
            [customFooter addSubview:label];
            [customFooter addSubview:priceLabel];
            return customFooter;
        }else{
            UIView *customFooter = [[UIView alloc]initWithFrame:CGRectZero];
            return customFooter;
        }
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!isLogin && productInCart == nil) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CartViewCellNoLogin"];
        if ([indexPath row] == 0) {
            cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:13];
            cell.textLabel.text = @"Your Shopping Cart lives to serve. Give it purpose fill it with books, CDs, videos, DVDs, toys, electronics, and more.";
            cell.textLabel.numberOfLines = 0;
            [cell.textLabel sizeToFit];
        }else{
            cell.textLabel.text = @"Already a customer? Sign in";
            cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        return cell;
    }else{
        //Init cell
        int row = [indexPath row];
        static NSString *CartCellIdentifier = @"CartCellIdentifier";
        UINib *nib = [UINib nibWithNibName:@"CartViewCell" bundle:nil];
        [self->tableView registerNib:nib forCellReuseIdentifier:CartCellIdentifier];
        CartViewCell *cell = [self->tableView dequeueReusableCellWithIdentifier:CartCellIdentifier];
        
        //Set cell data
        [cell setName:[[productInCart objectAtIndex:row] valueForKey:@"Name"]];
        [cell setPrice:[[productInCart objectAtIndex:row] valueForKey:@"Price"]];
        [cell setQty:[[productInCart objectAtIndex:row] valueForKey:@"Qty"]];
        [cell setProductID:[[productInCart objectAtIndex:row] valueForKey:@"ID"]];
        cell.delegate = self;
        NSData *data = [[productInCart objectAtIndex:row] valueForKey:@"Image"];
        [cell setImageData:data];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
}

#pragma mark Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = [indexPath row];
    if (!isLogin && productInCart == nil) {
        if (row == 1) {
            LoginViewController *nextController = [[LoginViewController alloc]init];
            [self.navigationController pushViewController:nextController animated:YES];
        }
    }else{
        NSInteger *productID = (NSInteger*)[[[productInCart objectAtIndex:row] valueForKey:@"ID"] integerValue];
        ProductDetailViewController *nextController = [[ProductDetailViewController alloc]init];
        [nextController setProductID:productID];
        [self.navigationController pushViewController:nextController animated:YES];
    }    
}


@end
